package com.mdinic.blogovi.ctrl;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.roo.addon.web.mvc.controller.finder.RooWebFinder;
import org.springframework.roo.addon.web.mvc.controller.scaffold.RooWebScaffold;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import com.mdinic.blogovi.model.Blog;

@RequestMapping("/blogs")
@Controller
@RooWebScaffold(path = "blogs", formBackingObject = Blog.class)
@RooWebFinder
public class BlogController {

    @RequestMapping(method = RequestMethod.POST, produces = "text/html")
    public String create(@Valid Blog blog, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, blog);
            return "blogs/create";
        }
        uiModel.asMap().clear();
        blog.persist();
        return "redirect:/admin/blogs/" + encodeUrlPathSegment(blog.getId().toString(), httpServletRequest);
    }

    @RequestMapping(params = "form", produces = "text/html")
    public String createForm(Model uiModel) {
        populateEditForm(uiModel, new Blog());
        return "blogs/create";
    }

    @RequestMapping(value = "/{id}", produces = "text/html")
    public String show(@PathVariable("id") Long id, Model uiModel) {
        uiModel.addAttribute("blog", Blog.findBlog(id));
        uiModel.addAttribute("itemId", id);
        return "blogs/show";
    }

    @RequestMapping(produces = "text/html")
    public String list(@RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        if (page != null || size != null) {
            int sizeNo = size == null ? 10 : size.intValue();
            final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
            uiModel.addAttribute("blogs", Blog.findBlogEntries(firstResult, sizeNo));
            float nrOfPages = (float) Blog.countBlogs() / sizeNo;
            uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
                    : nrOfPages));
        } else {
            uiModel.addAttribute("blogs", Blog.findAllBlogs());
        }
        return "blogs/list";
    }

    @RequestMapping(method = RequestMethod.PUT, produces = "text/html")
    public String update(@Valid Blog blog, BindingResult bindingResult, Model uiModel,
            HttpServletRequest httpServletRequest) {
        if (bindingResult.hasErrors()) {
            populateEditForm(uiModel, blog);
            return "blogs/update";
        }
        uiModel.asMap().clear();
        blog.merge();
        return "redirect:/admin/blogs/" + encodeUrlPathSegment(blog.getId().toString(), httpServletRequest);
    }

    @RequestMapping(value = "/{id}", params = "form", produces = "text/html")
    public String updateForm(@PathVariable("id") Long id, Model uiModel) {
        populateEditForm(uiModel, Blog.findBlog(id));
        return "blogs/update";
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "text/html")
    public String delete(@PathVariable("id") Long id, @RequestParam(value = "page", required = false) Integer page,
            @RequestParam(value = "size", required = false) Integer size, Model uiModel) {
        Blog blog = Blog.findBlog(id);
        blog.remove();
        uiModel.asMap().clear();
        uiModel.addAttribute("page", (page == null) ? "1" : page.toString());
        uiModel.addAttribute("size", (size == null) ? "10" : size.toString());
        return "redirect:/admin/blogs";
    }

    @RequestMapping(params = { "find=ByNameEquals", "form" }, method = RequestMethod.GET)
    public String findBlogsByNameEqualsForm(Model uiModel) {
        return "blogs/findBlogsByNameEquals";
    }

    @RequestMapping(params = "find=ByNameEquals", method = RequestMethod.GET)
    public String findBlogsByNameEquals(@RequestParam("name") String name, Model uiModel) {
        uiModel.addAttribute("blogs", Blog.findBlogsByNameEquals(name).getResultList());
        return "blogs/list";
    }

    @RequestMapping(params = { "find=ByNameLike", "form" }, method = RequestMethod.GET)
    public String findBlogsByNameLikeForm(Model uiModel) {
        return "blogs/findBlogsByNameLike";
    }

    @RequestMapping(params = "find=ByNameLike", method = RequestMethod.GET)
    public String findBlogsByNameLike(@RequestParam("name") String name, Model uiModel) {
        uiModel.addAttribute("blogs", Blog.findBlogsByNameLike(name).getResultList());
        return "blogs/list";
    }

    @RequestMapping(params = { "find=ByUrlEquals", "form" }, method = RequestMethod.GET)
    public String findBlogsByUrlEqualsForm(Model uiModel) {
        return "blogs/findBlogsByUrlEquals";
    }

    @RequestMapping(params = "find=ByUrlEquals", method = RequestMethod.GET)
    public String findBlogsByUrlEquals(@RequestParam("url") String url, Model uiModel) {
        uiModel.addAttribute("blogs", Blog.findBlogsByUrlEquals(url).getResultList());
        return "blogs/list";
    }

    @RequestMapping(params = { "find=ByUrlLike", "form" }, method = RequestMethod.GET)
    public String findBlogsByUrlLikeForm(Model uiModel) {
        return "blogs/findBlogsByUrlLike";
    }

    @RequestMapping(params = "find=ByUrlLike", method = RequestMethod.GET)
    public String findBlogsByUrlLike(@RequestParam("url") String url, Model uiModel) {
        uiModel.addAttribute("blogs", Blog.findBlogsByUrlLike(url).getResultList());
        return "blogs/list";
    }

    @RequestMapping(params = { "find=ByAutoApproveNot", "form" }, method = RequestMethod.GET)
    public String findBlogsByAutoApproveNotForm(Model uiModel) {
        return "blogs/findBlogsByAutoApproveNot";
    }

    @RequestMapping(params = "find=ByAutoApproveNot", method = RequestMethod.GET)
    public String findBlogsByAutoApproveNot(@RequestParam(value = "autoApprove", required = false) Boolean autoApprove,
            Model uiModel) {
        uiModel.addAttribute("blogs", Blog.findBlogsByAutoApproveNot(autoApprove == null ? Boolean.FALSE : autoApprove)
                .getResultList());
        return "blogs/list";
    }

    @RequestMapping(params = { "find=ByBlacklistedNot", "form" }, method = RequestMethod.GET)
    public String findBlogsByBlacklistedNotForm(Model uiModel) {
        return "blogs/findBlogsByBlacklistedNot";
    }

    @RequestMapping(params = "find=ByBlacklistedNot", method = RequestMethod.GET)
    public String findBlogsByBlacklistedNot(@RequestParam(value = "blacklisted", required = false) Boolean blacklisted,
            Model uiModel) {
        uiModel.addAttribute("blogs", Blog.findBlogsByBlacklistedNot(blacklisted == null ? Boolean.FALSE : blacklisted)
                .getResultList());
        return "blogs/list";
    }

    void populateEditForm(Model uiModel, Blog blog) {
        uiModel.addAttribute("blog", blog);
    }

    String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
        String enc = httpServletRequest.getCharacterEncoding();
        if (enc == null) {
            enc = WebUtils.DEFAULT_CHARACTER_ENCODING;
        }
        try {
            pathSegment = UriUtils.encodePathSegment(pathSegment, enc);
        } catch (UnsupportedEncodingException uee) {
        }
        return pathSegment;
    }
}
